
/*   RolGPS Project
 * 
 *   Copyright (C) 2009 Pablo Alejandro Costesich <rhfixer@gmail.com>
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */
package org.rolgps.libnlink.connection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Observable;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.rolgps.libnstack.parser.ParserFactory;
import org.rolgps.libnstack.protocol.Message;
import org.rolgps.libnstack.protocol.MessageParser;

/**
 *
 * @author xeph
 */
class SocketListener extends Observable implements Runnable {

    Socket socket = null;
    boolean exit = false;
    MessageParser parserEngine = ParserFactory.getDefaultParser();

    /**
     *
     * @param socket
     */
    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    void shutdown(){
        setChanged();
        notifyObservers(CommEvent.SHUTDOWN);
        exit=true;
    }

    public void run() {
        BufferedReader input = null;
        try {
            Message receivedMessage = null;
            input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (input != null && !exit) {
                receivedMessage = parserEngine.parseString(input);
                if(receivedMessage.getHeader("type").length == 1 &&
                        receivedMessage.getHeader("type")[0].equals("SYS") &&
                        receivedMessage.getHeader("status").length == 1 &&
                        receivedMessage.getHeader("status")[0].equals("ERR")){
                    setChanged();
                    notifyObservers(CommEvent.EXCEPTION);
                }else{
                    setChanged();
                    notifyObservers(receivedMessage);
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(SocketListener.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                Logger.getLogger(SocketListener.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
